package com.yaozheng.vocationaltraining.activity;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.SeekBarProgressChange;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.DimensionPixelSizeRes;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

//import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.adapter.ImageListCoursewareDetailAdapter;
import com.yaozheng.vocationaltraining.iview.ICoursewarePaperView;
import com.yaozheng.vocationaltraining.iview.IItemView;
import com.yaozheng.vocationaltraining.iview.IVideoCoursewareOperatingView;
import com.yaozheng.vocationaltraining.iview.IVideoCoursewareView;
import com.yaozheng.vocationaltraining.iview.collect.IMyCollectAddView;
import com.yaozheng.vocationaltraining.service.CoursewareDetailOperatingService;
import com.yaozheng.vocationaltraining.service.CoursewareDetailService;
import com.yaozheng.vocationaltraining.service.CoursewarePaperService;
import com.yaozheng.vocationaltraining.service.collect.MyCollectAddService;
import com.yaozheng.vocationaltraining.service.impl.CoursewareDetailOperatingServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.CoursewareDetailServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.CoursewarePaperServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.collect.MyCollectAddServiceImpl;
import com.yaozheng.vocationaltraining.utils.ACache;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ControlsUtils;
import com.yaozheng.vocationaltraining.utils.JsonUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.view.VideoCoursewareDetailView;

/**
 * 图片列表课件详情
 *
 * @author Administrator
 */
@EActivity(R.layout.activity_image_list_courseware_detail)
public class
        ImageListCoursewareDetailActivity extends BaseActivity implements
        OnPageChangeListener, IVideoCoursewareView,
        IVideoCoursewareOperatingView, IItemView, ICoursewarePaperView, IMyCollectAddView {
    @Extra
    String title;
    @ViewById
    ViewPager coursewareViewpager;
    @ViewById
    ImageView leftImage, rightImage, fullScreenImage, headRightImage;
    @ViewById
    TextView coursewareTitleText, coursewareProgressTextView;
    @ViewById
    SeekBar coursewareProgressSeekBar;
    @ViewById
    VideoCoursewareDetailView coursewareDetailView;
    @ViewById
    View customVideoViewLayout, scrollView, coursewareFullScreenBottomLayout, coursewareFullScreenHeadLayout;
    @DimensionPixelSizeRes(R.dimen.video_courseware_image_height)
    int videoCoursewareImageHeight;
    @DimensionPixelSizeRes(R.dimen.default_margin)
    int defaultMargin;
    /**
     * 课件详情服务
     */
    @Bean(CoursewareDetailServiceImpl.class)
    CoursewareDetailService coursewareDetailService;
    /**
     * 课件详情操作服务(上次记录)
     */
    @Bean(CoursewareDetailOperatingServiceImpl.class)
    CoursewareDetailOperatingService coursewareDetailOperatingService;
    /**
     * 课件对应试卷服务
     */
    @Bean(CoursewarePaperServiceImpl.class)
    CoursewarePaperService coursewarePaperService;

    @Bean(MyCollectAddServiceImpl.class)
    MyCollectAddService myCollectAddService;

    JSONObject currCourserJsonObject, courserJsonObject;

    ImageListCoursewareDetailAdapter imageListCoursewareDetailAdapter;
    /**
     * 是否显示菜单
     */
    boolean isShowMenu;
    /**
     * 是否全屏
     */
    boolean isFullScreen;

    int currScreenWidth;
    /**
     * 图片长度
     */
    int imagesLeng;

    ACache aCache;

    String userName;

    @AfterViews
    public void initView() {
        setHeadTitle(title);

        coursewareViewpager.setOnPageChangeListener(this);
        coursewareDetailOperatingService.init(this);
        coursewareDetailService.init(this);
        coursewarePaperService.init(this);
        coursewareDetailView.init(this);
        myCollectAddService.init(this);

        isFullScreen = false;
        currScreenWidth = ControlsUtils.getCurrScreeWidth(this);
        coursewareProgressSeekBar.setEnabled(true);
        aCache = ACache.get(this);
        userName = aCache.getAsString("userName");
        loadData();
        //下载按钮隐藏
        coursewareDetailView.getCoursewareOperatingBut().setVisibility(
                View.GONE);
        headRightImage.setVisibility(View.VISIBLE);
    }


    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 在横屏的情况下,跳转
            RelativeLayout.LayoutParams scrollViewLayoutPara = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    currScreenWidth);
            scrollView.setLayoutParams(scrollViewLayoutPara);
            //全屏头部显示
            coursewareFullScreenHeadLayout.setVisibility(View.VISIBLE);
            //全屏尾部显示
            coursewareFullScreenBottomLayout.setVisibility(View.VISIBLE);
            //全屏按钮隐藏
            fullScreenImage.setVisibility(View.GONE);

            LinearLayout.LayoutParams customVideoViewLayoutPara = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    currScreenWidth);
            customVideoViewLayout.setLayoutParams(customVideoViewLayoutPara);
            RelativeLayout.LayoutParams surfaceLayoutParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    currScreenWidth);
            coursewareViewpager.setLayoutParams(surfaceLayoutParams);
            coursewareDetailView.setVisibility(View.GONE);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            isFullScreen = true;

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

            RelativeLayout.LayoutParams scrollViewLayoutPara = new RelativeLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.FILL_PARENT);
            scrollViewLayoutPara.addRule(RelativeLayout.BELOW, R.id.headLayout);
            scrollView.setLayoutParams(scrollViewLayoutPara);
            //半屏头部隐藏
            coursewareFullScreenHeadLayout.setVisibility(View.GONE);
            //半屏尾部隐藏
            coursewareFullScreenBottomLayout.setVisibility(View.GONE);
            //半屏按钮显示
            fullScreenImage.setVisibility(View.VISIBLE);

            // 在竖直情况下，跳转
            LinearLayout.LayoutParams customVideoViewLayoutPara = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    videoCoursewareImageHeight);
            int defaultMargin = 0;

//                    getResources().getDimensionPixelOffset(
//                    R.dimen.default_margin);
            customVideoViewLayoutPara.setMargins(defaultMargin, 0,
                    defaultMargin, 0);

            customVideoViewLayout.setLayoutParams(customVideoViewLayoutPara);

            RelativeLayout.LayoutParams surfaceLayoutParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    videoCoursewareImageHeight);

            coursewareDetailView.setVisibility(View.VISIBLE);
            coursewareViewpager.setLayoutParams(surfaceLayoutParams);
            getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
            getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            isFullScreen = false;


        }
        full(isFullScreen);
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 设置是否隐藏状态栏
     *
     * @param enable
     */
    private void full(boolean enable) {
        if (enable) {
            // 隐藏状态栏
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);

        } else {
            // 显示状态栏
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            // getWindow().clearFlags(
            // WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        }
    }

    /**
     * 加载数据
     */
    public void loadData() {
        boolean isLoadNew = getIntentBoolean("isLoadNew", true);
        courserJsonObject = JsonUtils
                .getJsonObject(getIntentString("courserJsonStr"));
        if (isLoadNew) {

            courserJsonObject.remove("format");
            coursewareTitleText.setText(TypeUtils.getJsonString(
                    courserJsonObject, "subject", ""));
            coursewareDetailView
                    .setVideoCoursewareDetailText(courserJsonObject);
            coursewareDetailService.getCourse(TypeUtils.getJsonInteger(
                    courserJsonObject, "id"));

        } else {
            this.currCourserJsonObject = courserJsonObject;
            updateData();
        }
    }

    /**
     * 隐藏提示图片
     */
    public void hidePromptImage() {
        isShowMenu = false;
        leftImage.setVisibility(View.GONE);
        rightImage.setVisibility(View.GONE);

        if (isFullScreen) {
            //全屏隐藏菜单
            coursewareFullScreenHeadLayout.setVisibility(View.GONE);
            coursewareFullScreenBottomLayout.setVisibility(View.GONE);
        } else {
            //半屏隐藏全屏按钮
            fullScreenImage.setVisibility(View.GONE);
        }

    }

    /**
     * 隐藏提示图片
     */
    public void showPromptImage() {
        isShowMenu = true;
        leftImage.setVisibility(View.VISIBLE);
        rightImage.setVisibility(View.VISIBLE);
        if (isFullScreen) {
            //全屏显示菜单
            coursewareFullScreenHeadLayout.setVisibility(View.VISIBLE);
            coursewareFullScreenBottomLayout.setVisibility(View.VISIBLE);
        } else {
            //半屏显示全屏按钮
            fullScreenImage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int position) {
        coursewareProgressSeekBar.setProgress(position + 1);
        coursewareProgressTextView.setText(getString(R.string.imageCoursewareProgressStr, position + 1, imagesLeng));

        // if (arg0 == 1) {
//        hidePromptImage();
        // }
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        cancelLoadDataProgressDialog();
        JSONObject courserJsonObject = TypeUtils.getJsonObject(jsonObject,
                "data", "course");
        if (courserJsonObject != null) {

            this.currCourserJsonObject = courserJsonObject;
            updateData();
        }
    }

    /**
     * 更新数据
     */
    public void updateData() {
        if (this.currCourserJsonObject != null) {
//            System.out.println("--------" + courserJsonObject.toString());
            coursewareTitleText.setText(TypeUtils.getJsonString(
                    courserJsonObject, "subject", ""));
            coursewareDetailView
                    .setVideoCoursewareDetailText(currCourserJsonObject);

            JSONArray dataList = TypeUtils
                    .getJsonArray(TypeUtils.getJsonObject(
                            currCourserJsonObject, "resources"), "images");
            imagesLeng = TypeUtils.getJsonArraySize(dataList);
            coursewareProgressSeekBar.setMax(imagesLeng);
            if (imageListCoursewareDetailAdapter == null) {
                imageListCoursewareDetailAdapter = new ImageListCoursewareDetailAdapter(
                        this, getSupportFragmentManager(), dataList, this, userName);
                coursewareViewpager
                        .setAdapter(imageListCoursewareDetailAdapter);
                SharedPreferences sharedPreferences = getCurrUserSharedPreferences();
                int id = TypeUtils.getJsonInteger(currCourserJsonObject, "id");
                int currentPosition = sharedPreferences.getInt("id_" + id, 0);
                if (currentPosition > 0) {
                    coursewareViewpager.setCurrentItem(currentPosition);
                }

                showPromptImage();
            }
        }
    }


    /**
     * 随堂考试
     */
    @Click(R.id.coursewareQuizText)
    public void quizExamClick() {
        coursewarePaperService.craetePaper(String.valueOf(getIntentInt("subCatId")));
    }

    @Override
    public void createPaperSuccess(JSONObject jsonObject) {
        this.cancelOperatingProgressDialog();
        JSONObject paperJsonObject = TypeUtils.getJsonObject(jsonObject, "data", "paper");
        String id = TypeUtils.getJsonString(paperJsonObject, "id");
        Intent intent = new Intent();
        intent.setClassName(this,
                Constants.ONLINE_EXAM_ACTIVITY_CLASS_NAME);
        intent.putExtra("examType", "2");
        intent.putExtra("paperId", id);
        intent.putExtra("questionJsonObject", paperJsonObject.toString());
        startActivityForResult(intent, Constants.ONLINE_EXAM_RESULT_CODE);
//        paperId
//        System.out.println("-------" + jsonObject);
    }


    @UiThread
    @Override
    public void createPaperError(String error) {
        this.cancelOperatingProgressDialog();
        alertMessage(error);
    }

    @UiThread
    @Override
    public void responseError(String error) {
        // TODO Auto-generated method stub
        cancelLoadDataProgressDialog();
        alertMessage(error);

    }

    @Override
    public boolean isResponseResult() {
        return !isFinishing();
    }

    @Override
    public String getLocalVideoCacheDir() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void downloadVideoError(String error) {
        // TODO Auto-generated method stub

    }

    @Override
    public void downloadStatusChange(double completionRate) {
        // TODO Auto-generated method stub

    }

    @Override
    public void downloadSuccess() {
        // TODO Auto-generated method stub

    }

    @Override
    public void coursewareOperatingButClick() {
        // TODO Auto-generated method stub

    }

    @Override
    public void saveProgressSuccess(JSONObject jsonObject) {
        // TODO Auto-generated method stub

    }

    @Override
    public void saveProgressError(String error) {
        // TODO Auto-generated method stub

    }

    @Override
    public void submitServerDownloadSuccess(JSONObject jsonObject) {
        // TODO Auto-generated method stub

    }

    @Override
    public void submitServerDownloadError(String error) {
        // TODO Auto-generated method stub

    }

    /**
     * 收藏点击
     */
    public void rightClick() {
        showConfirmCancelAskDialog("是否收藏" + TypeUtils.getJsonString(
                courserJsonObject, "subject") + "课件?");
    }

    /**
     * 确定取消 询问对话确定点击
     */
    public void confirmCancelAskDialogDetermineClick() {
        addCollectOperating();
    }

    /**
     * 添加收藏操作
     */
    public void addCollectOperating() {
        showOperatingProgressDialog("收藏中...");
        if (courserJsonObject != null) {
            myCollectAddService.addCollect(1, TypeUtils.getJsonInteger(
                    courserJsonObject, "id"));
        }
    }

    @UiThread
    @Override
    public void addCollectSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        boolean result = TypeUtils.getJsonBoolean(TypeUtils.getJsonObject(jsonObject, "data"), "result", false);
        if (result) {
            alertMessage("收藏成功!");
        } else {
            alertMessage("收藏失败!请与服务器管理员联系");
        }
    }

    @UiThread
    @Override
    public void addCollectError(String error) {
        cancelOperatingProgressDialog();
        alertMessage(error);
    }

    @Override
    public void itemClick(int position) {
        if (isShowMenu) {
            hidePromptImage();
        } else {
            showPromptImage();
        }
    }

    @Click(R.id.fullScreenImage)
    public void fullScreenClick() {
        /*
        if (isFullScreen) {
            // 退出全屏
            coursewareTitleText.setVisibility(View.VISIBLE);
            LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    videoCoursewareImageHeight);
            layout.setMargins(defaultMargin, 0, defaultMargin, 0);

            customVideoViewLayout.setLayoutParams(layout);
            isFullScreen = false;

        } else {

            LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.FILL_PARENT);
            // layout.setMargins(0, 0, 0, 0);

            customVideoViewLayout.setLayoutParams(layout);
            coursewareTitleText.setVisibility(View.GONE);
            isFullScreen = true;
            // 全屏
        }*/
        if (isFullScreen) {
            // 退出全屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            // 全屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        imageListCoursewareDetailAdapter.setFullScreen(isFullScreen);
        imageListCoursewareDetailAdapter.notifyDataSetChanged();
    }

    @SeekBarProgressChange(R.id.coursewareProgressSeekBar)
    public void onProgressChangeOnSeekBar(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            coursewareViewpager.setCurrentItem(progress);
        }
    }

    @Override
    protected void onPause() {
        if (isFullScreen) {
            fullScreenClick();
        }
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        if (isFullScreen) {
            fullScreenClick();
            return;
        }
        exitSaveRecording();
        setResult(Constants.RESULT_OK_REFRESH_DATA);
        super.onBackPressed();
    }

    /**
     * 退出保存记录
     */
    public void exitSaveRecording() {
        if (currCourserJsonObject != null) {
            int currentPosition = coursewareViewpager.getCurrentItem();
            SharedPreferences sharedPreferences = getCurrUserSharedPreferences();
            Editor editor = sharedPreferences.edit();
            int id = TypeUtils.getJsonInteger(currCourserJsonObject, "id");
            coursewareDetailOperatingService.saveProgress(id, currentPosition + 1);
            editor.putInt(
                    "id_"
                            + TypeUtils.getJsonInteger(currCourserJsonObject,
                            "id"), currentPosition);
            editor.commit();
            currCourserJsonObject = null;
        }
    }


    @Override
    protected void onDestroy() {
        exitSaveRecording();
        super.onDestroy();
    }
}
